package com.ruanmeng.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothProfile;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.provider.Settings;
import android.support.annotation.RequiresApi;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.svprogresshud.SVProgressHUD;
import com.com.ruanmeng.demon.CommonM;
import com.com.ruanmeng.demon.GetLastXLM;
import com.com.ruanmeng.demon.SYM;
import com.com.ruanmeng.utils.CommonUtil;
import com.com.ruanmeng.utils.ImgDataUtil;
import com.com.ruanmeng.utils.Params;
import com.com.ruanmeng.utils.PreferencesUtils;
import com.com.ruanmeng.utils.ToolUtils;
import com.com.ruanmeng.view.GridRelativeLayout;
import com.com.ruanmeng.view.ImageCycleView;
import com.com.ruanmeng.view.LineView;
import com.example.lenovo.weiyi.BaseActivity;
import com.example.lenovo.weiyi.LunBoXQActivity;
import com.example.lenovo.weiyi.R;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.rest.Request;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import bluetooth.BleDefinedUUIDs;
import bluetooth.BltContant;
import bluetooth.BltManager;
import butterknife.BindView;
import butterknife.ButterKnife;
import nohttp.CallServer;
import nohttp.CustomHttpListener;
import share.Const;
import share.HttpIP;


@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
public class KangFuFragment extends Fragment implements View.OnClickListener {


    @BindView(R.id.ic_fragment_kf_lunbo)
    ImageCycleView LunBo;
    @BindView(R.id.li_kfzd_start)
    LinearLayout liKfzdStart;
    @BindView(R.id.li_kfzd_music)
    LinearLayout liKfzdMusic;
    @BindView(R.id.li_kfzd_zixun)
    LinearLayout liKfzdZixun;
    @BindView(R.id.rl_sy_refresh)
    SwipeRefreshLayout mRefresh;
    @BindView(R.id.pc_title)
    View pcTitle;
    private View fview;
    private HorizontalScrollView scrollview;
    LinearLayout li_xl_y, li_xl_x, li_xl_cback;
    private LineView mLineView, mtLineView, mfLineView;
    private String StartTimeWithFormat;
    int Continue_Time = 3600;//持续时间
    int Continue = 5;//间隔单位
    private static final int MSG_DATA_CHANGE = 0x11;
    private int mX = 0;
    private LinearLayout li_kfzd_bstart;
    private TextView tv_kf_bstart;
    private int StartXl;
    private int arg1_X;
    private int arg1_Y;
    private TextView tv_starttime;
    private TextView tv_endtime;
    private BluetoothAdapter mBluetoothAdapter;
    private Boolean HaveClectNum = false;
    double TvHeight = 39.6;
//    double TvHeight = 39.6;
    //xinlv
    ArrayList<Integer> Temp_XL = new ArrayList<>();
    private SVProgressHUD progress;
    TextView tv_bottom_now, tv_bottom_max, tv_bottom_evel;
    GridRelativeLayout rl;
    private int age, bigHeartRate, RedHeartRateStart, YellowHeartRateStart, GreenHeartRateStart, BlueHeartRateStart, GrayHeartRateStart;

    //关于蓝牙特征码
    String HEART_RATE_SERVICE = "180D";
    String HEART_RATE_MEASUREMENT = "2A37";
    private long StartTime;
    private long EndTime;
    private PowerManager.WakeLock wl;

    public static KangFuFragment instantiation() {
        KangFuFragment fragment = new KangFuFragment();
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO Auto-generated method stub
//        getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);//屏幕常亮
        fview = inflater.inflate(R.layout.kangfu_fragment_layout, null);
        ButterKnife.bind(this, fview);
        PowerManager pm = (PowerManager) getActivity().getSystemService(Context.POWER_SERVICE);
        wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "MyTag");
        getnum();
        initView(fview);
        initXL(fview);
        getLastXLData();
        return fview;
    }

    public void getnum() {
        /**
         * 红色：≥96%最大心率；
         * 黄色：76-96%最大心率；
         * 绿色：64-76%最大心率；
         * 蓝色：57-64%最大心率；
         * 灰色：＜57%最大心率；
         * 最大心率：207-0.7*年龄
         */
        age = Integer.parseInt(PreferencesUtils.getString(getActivity(), "age"));
        bigHeartRate = (int) (207 - 0.7 * age);
        RedHeartRateStart = (int) (bigHeartRate * 0.96);
        YellowHeartRateStart = (int) (bigHeartRate * 0.76);//143
        GreenHeartRateStart = (int) (bigHeartRate * 0.64);//120
        BlueHeartRateStart = (int) (bigHeartRate * 0.57);
        GrayHeartRateStart = 0;
        int aa = ToolUtils.dp2px(getActivity(), 16);//396
        int bb = ToolUtils.dp2px(getActivity(), 198);//396
    }

    private void initView(View vfview) {
        mRefresh.setColorSchemeResources(R.color.MainColor);
        mRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getData();
            }
        });
        //轮播图
        LunBo.setAutoCycle(true);/////设置是否自动轮播
        WindowManager windowManager = getActivity().getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        int screenWidth = display.getWidth();
        int hei = (int) (screenWidth / 2);
        LinearLayout.LayoutParams rlay_params = new LinearLayout.LayoutParams(
                screenWidth, hei);
        LunBo.setLayoutParams(rlay_params);
    }

    /**
     * 关于心率
     *
     * @param v
     */
    public void initXL(View v) {
        //Y
        scrollview = (HorizontalScrollView) v.findViewById(R.id.scrollview);
        li_kfzd_bstart = (LinearLayout) v.findViewById(R.id.li_kfzd_bottomstart);
        tv_kf_bstart = (TextView) v.findViewById(R.id.tv_kf_bstart);
        tv_starttime = (TextView) v.findViewById(R.id.tv_bottom_starttime);
        tv_endtime = (TextView) v.findViewById(R.id.tv_bottom_endtime);
        //Y
        li_xl_y = (LinearLayout) v.findViewById(R.id.li_xl_y);
        //X
        li_xl_x = (LinearLayout) v.findViewById(R.id.li_xl_x);
        //中间大背景
        li_xl_cback = (LinearLayout) v.findViewById(R.id.li_xl_centerbackground);
        //网格
        rl = (GridRelativeLayout) v.findViewById(R.id.rl);
        //当前心率
        tv_bottom_now = (TextView) v.findViewById(R.id.tv_bottom_now);
        tv_bottom_max = (TextView) v.findViewById(R.id.tv_bottom_max);
        tv_bottom_evel = (TextView) v.findViewById(R.id.tv_bottom_evel);
        setY();
        setX(Continue_Time);
        mLineView = (LineView) v.findViewById(R.id.line);
        mtLineView = (LineView) v.findViewById(R.id.line_t);
        mfLineView = (LineView) v.findViewById(R.id.line_f);
        //由于安卓默认圆点是左上角   将Y轴坐标做处理是的坐标点转移到左下角
        //康复指导页-心率图，Y轴从上往下第三第四个数字位置增加两条横线，（即心率40%与60%位置）
        mtLineView.setLinePoint(0, getHeight(107));
        mtLineView.setLinePoint(1, getHeight(107));
        mtLineView.setLinePoint(2, getHeight(107));
        mtLineView.setLinePoint(3, getHeight(107));
        mtLineView.setLinePoint(4, getHeight(107));
        mtLineView.setLinePoint(5, getHeight(107));
        mtLineView.setcolor(Color.YELLOW);
        setListener();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    public void setListener() {
        li_kfzd_bstart.setOnClickListener(this);
    }

    private void getData() {
        Request<String> mRequest = NoHttp.createStringRequest(HttpIP.SY, Const.POST);
        mRequest.addHeader("token", PreferencesUtils.getString(getActivity(), "uid"));
        CallServer.getRequestInstance().add(getActivity(), 0, mRequest,
                new CustomHttpListener(getActivity(), true, SYM.class) {

                    @Override
                    public void doWork(Object data, boolean isOne) {
                        final SYM model = ((SYM) data);
                        //轮播图
                        final List<SYM.ObjectBean.SlidersBean> Temp_Lunbo = model.getObject().getSliders();
                        LunBo.loadData(Temp_Lunbo.size(), new ImageCycleView.LoadImageCallBack() {
                            @Override
                            public void loadAndDisplay(ImageView iv, int position) {
                                ImgDataUtil.loadLunboImage(getActivity(), HttpIP.Base_IpIMage + Temp_Lunbo.get(position).getSliderImg(), iv);
                            }
                        });
                        LunBo.setOnPageClickListener(new ImageCycleView.OnPageClickListener() {
                            @Override
                            public void onClick(View imageView, int position) {
                                if (Temp_Lunbo.get(position).getHref() != null && !TextUtils.isEmpty(Temp_Lunbo.get(position).getHref())) {
                                    Uri uri = Uri.parse(Temp_Lunbo.get(position).getHref());
                                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                                    startActivity(intent);
                                } else if (!TextUtils.isEmpty(model.getObject().getSliders().get(position).getContent())) {
                                    Intent in = new Intent(getActivity(), LunBoXQActivity.class);
                                    in.putExtra("title", Temp_Lunbo.get(position).getSliderTitle());
                                    in.putExtra("content", Temp_Lunbo.get(position).getContent());
                                    startActivity(in);
                                }
                            }
                        });
                    }

                    @Override
                    public void onFinally(JSONObject obj) throws JSONException {
                        super.onFinally(obj);
                        mRefresh.setRefreshing(false);
                    }
                }, true, true);
    }

    /**
     * 添加心率
     */
    private void getXLData() {
        SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
        Date curDate = new Date(StartTime);//获取当前时间
        String str = formatter.format(curDate);
        Request<String> mRequest = NoHttp.createStringRequest(HttpIP.ADDXL, Const.POST);
        mRequest.addHeader("token", PreferencesUtils.getString(getActivity(), "uid"));
        mRequest.add("heartValue", XinLv_str());//心率值
        mRequest.add("heartAvg", tv_bottom_evel.getText().toString().replace("次/分", ""));//平均
        mRequest.add("beginDate", tv_starttime.getText().toString());//运动时长
        mRequest.add("endDate", tv_endtime.getText().toString());//有效时长
        mRequest.add("heartMax", tv_bottom_max.getText().toString().replace("次/分", ""));//最大值
        mRequest.add("startDate", StartTimeWithFormat);//开始记录的时间
        CallServer.getRequestInstance().add(getActivity(), 0, mRequest,
                new CustomHttpListener(getActivity(), true, CommonM.class) {

                    @Override
                    public void doWork(Object data, boolean isOne) {
                        final CommonM model = ((CommonM) data);
                    }

                    @Override
                    public void onFinally(JSONObject obj) throws JSONException {
                        super.onFinally(obj);
                        if (!"100".equals(obj.getString("msgcode"))) {
                            CommonUtil.showToask(getActivity(), obj.getString("msg"));
                        }
                    }
                }, true, false);
    }

    /**
     * 获取上次的心率并显示
     */
    private void getLastXLData() {
        Request<String> mRequest = NoHttp.createStringRequest(HttpIP.GetLastXL, Const.POST);
        mRequest.addHeader("token", PreferencesUtils.getString(getActivity(), "uid"));
        CallServer.getRequestInstance().add(getActivity(), 0, mRequest,
                new CustomHttpListener(getActivity(), true, GetLastXLM.class) {

                    @Override
                    public void doWork(Object data, boolean isOne) {
                        final GetLastXLM model = ((GetLastXLM) data);
                        if (model.getObject() != null) {
                            tv_bottom_max.setText(model.getObject().getHeartMax() + "次/分");
                            tv_bottom_now.setText("0次/分");
                            tv_bottom_evel.setText(model.getObject().getHeartAvg() + "次/分");
                            tv_starttime.setText(model.getObject().getBeginDate());
                            tv_endtime.setText(model.getObject().getEndDate());
                            if (!TextUtils.isEmpty(model.getObject().getHeartValue())) {
                                String[] str = model.getObject().getHeartValue().split(",");
                                for (int i = 0; i < str.length; i++) {
                                    mLineView.setLinePoint(i, getHeight(Integer.parseInt(str[i])));
//                                    mLineView.setLinePoint(i, Integer.parseInt(str[i]));
                                }
                            }
                        }
                    }

                    @Override
                    public void onFinally(JSONObject obj) throws JSONException {
                        super.onFinally(obj);
                        if (!"100".equals(obj.getString("msgcode"))) {
                            CommonUtil.showToask(getActivity(), obj.getString("msg"));
                        }
                    }
                }, true, false);
    }


    /**
     * 获取心率值
     */
    public String XinLv_str() {
        StringBuilder buffer = new StringBuilder("");
        for (int i = 0; i < Temp_XL.size(); i++) {
            buffer.append(Temp_XL.get(i));
            if (i != Temp_XL.size() - 1) {
                buffer.append(",");
            }
        }
        return buffer.toString();
    }


    /**
     * 关于心率图
     */
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    //在获取心率后在显示
                    if (Temp_XL.size() > 0 && Temp_XL.size() > mX && "结束锻炼".equals(tv_kf_bstart.getText().toString())) {
                        if (mX == 0) {
                            StartTime = System.currentTimeMillis();
                            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            StartTimeWithFormat = format.format(new Date(StartTime));
                        }
                        tv_endtime.setText(GetUseableTime());//有效时长为心率大于64%的时间累计
                        if (progress != null) {
                            progress.dismiss();
                        }
                        mLineView.setLinePoint(mX, getHeight(Temp_XL.get(Temp_XL.size() - 1)));//显示的当前最新的
                        System.out.println("心率****====" + mX + "Y====" + getHeight(Temp_XL.get(Temp_XL.size() - 1)));
                        tv_starttime.setText(ToolUtils.formatTime(mX));
                        getMath();
                        mX += 1;
                        if (mX > 15) {//超出屏幕则移动
                             float XScale = (float)(16 * getResources().getDisplayMetrics().density + 0.5f);  //刻度长度
                            scrollview.scrollTo((int) (XScale * (mX - 10)), 0);
                        }
                    }
                    mHandler.sendEmptyMessageDelayed(0, 1000);
                    break;
                default:
                    break;
            }
            super.handleMessage(msg);
        }
    };

    /**
     * 最大心率
     */
    public void getMath() {
        int i, min, max;

        max = Temp_XL.get(0);
        System.out.print("数组A的元素包括：");
        for (i = 0; i < Temp_XL.size(); i++) {
            if (Temp_XL.get(i) > max)   // 判断最大值
                max = Temp_XL.get(i);
        }
        int all = 0;
        //平均值
        for (int j = 0; j < Temp_XL.size(); j++) {
            all += Temp_XL.get(j);
        }
        tv_bottom_max.setText(max + "次/分");
        tv_bottom_now.setText(Temp_XL.get(mX) + "次/分");
        if (mX != 0) {
            tv_bottom_evel.setText(all / Temp_XL.size() + "次/分");
        }
    }

    private Handler mHandler_m = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    if (Temp_XL.size() == 0) {
                        BltManager.getInstance().stopSearthBltDevice();//暂停搜索设备
                        CommonUtil.showToask(getActivity(), "未检测到已连接的心率设备！");
                        tv_kf_bstart.setText("开始锻炼");
                        wl.release();
                        Params.IsWakeClock = 0;
                        if (progress != null) {
                            progress.dismiss();
                        }
                    }
                    break;
                default:
                    break;
            }
            super.handleMessage(msg);
        }
    };

    /**
     * Y轴
     * 暂定  总高度198  下面  50    上面四个平分37
     */
    @SuppressLint("ResourceType")
    public void setY() {
        for (int i = 0; i < 6; i++) {
            View v = getActivity().getLayoutInflater().inflate(R.layout.textview_layout, null);
            TextView tv_tv = (TextView) v.findViewById(R.id.tv_tvy);
            View view_line = (View) v.findViewById(R.id.view_lineblack);
            //大背景
            View vi = getActivity().getLayoutInflater().inflate(R.layout.view_layout, null);
            View view = (View) vi.findViewById(R.id.view);
            if (i == 5) {
                tv_tv.setText(GrayHeartRateStart + "");
                view_line.setVisibility(View.GONE);
            } else if (i == 4) {
                tv_tv.setText(BlueHeartRateStart + "");
                setSize(tv_tv, "Y", TvHeight, view);
                view_line.setVisibility(View.VISIBLE);
                view.setBackgroundColor(getResources().getColor(R.color.XL_Gray));
                view_line.setBackgroundColor(getResources().getColor(R.color.Black));
            } else if (i == 3) {
                tv_tv.setText(GreenHeartRateStart + "");
                setSize(tv_tv, "Y", TvHeight, view);
                view_line.setVisibility(View.VISIBLE);
                view.setBackgroundColor(getResources().getColor(R.color.XL_Blue));
                view_line.setBackgroundColor(getResources().getColor(R.color.XL_Yellow));
            } else if (i == 2) {
                tv_tv.setText(YellowHeartRateStart + "");
                view_line.setVisibility(View.VISIBLE);
                setSize(tv_tv, "Y", TvHeight, view);
                view.setBackgroundColor(getResources().getColor(R.color.XL_Green));
                view_line.setBackgroundColor(getResources().getColor(R.color.XL_Yellow));
            } else if (i == 1) {
                tv_tv.setText(RedHeartRateStart + "");
                view_line.setVisibility(View.VISIBLE);
                setSize(tv_tv, "Y", TvHeight, view);
                view.setBackgroundColor(getResources().getColor(R.color.XL_Yellow));
                view_line.setBackgroundColor(getResources().getColor(R.color.Black));
            } else {
                tv_tv.setText(bigHeartRate + "");
                view_line.setVisibility(View.VISIBLE);
                setSize(tv_tv, "Y", TvHeight, view);
                view.setBackgroundColor(getResources().getColor(R.color.XL_Red));
                view_line.setBackgroundColor(getResources().getColor(R.color.Black));

            }
            li_xl_y.addView(v);
            li_xl_cback.addView(vi);
        }
    }

    /**
     * X轴
     */
    public void setX(int size_x) {
        int numx = 0;
        if (size_x % Continue != 0) {
            numx = size_x / Continue + 1;
        } else {
            numx = size_x / Continue;
        }
        for (int i = 0; i < numx; i++) {
            View vx = getActivity().getLayoutInflater().inflate(R.layout.textview_layoutx, null);
            TextView tv_tv = (TextView) vx.findViewById(R.id.tv_tvx);
            tv_tv.setText((i + 1) * Continue + "");
            li_xl_x.addView(vx);
        }
        float a = ToolUtils.dip2px(getActivity(), 300);//Y轴总长400.5
        float num = (float) 300 / bigHeartRate;
        double b = ToolUtils.dip2px(getActivity(), (float) (300 / bigHeartRate));//Y轴刻度(次数（1）300/300)   2.5
        double c = ToolUtils.dip2px(getActivity(), 80 / 5);//X轴刻度（分钟）32.5
        //画网格
        //measure方法的参数值都设为0即可
        li_xl_x.measure(0, 0);
        //获取组件宽度
        int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        li_xl_x.measure(w, h);
        int width = li_xl_x.getMeasuredWidth();
        int we = ToolUtils.dp2px(getActivity(), 80);
        rl.setInf(we / 5, we / 5, width, 720);//画网格线
    }

    /**
     * 设置控件高度
     */
    public void setSize(TextView tv, String type_str, double bou, View v) {
        LinearLayout.LayoutParams linearParams = (LinearLayout.LayoutParams) tv.getLayoutParams(); //取控件textView当前的布局参数
        LinearLayout.LayoutParams linearParamsv = (LinearLayout.LayoutParams) v.getLayoutParams(); //取控件textView当前的布局参数
        if ("Y".equals(type_str)) {
            linearParams.height = ToolUtils.dip2px(getActivity(), bou);
            linearParams.width = ToolUtils.dip2px(getActivity(), 30);
            tv.setLayoutParams(linearParams); //使设置好的布局参数应用到控件</pre>
            linearParamsv.height = ToolUtils.dip2px(getActivity(), bou);
            linearParamsv.width = ToolUtils.dip2px(getActivity(), 80 * (Continue_Time / Continue));
            v.setLayoutParams(linearParamsv); //使设置好的布局参数应用到控件</pre>
        }
    }

    /**
     * 计算高度
     * 57%的刻度   BlueHeartRateStart/50
     * 上部四部分的刻度     /37
     * int_Y    dp
     */
    public int getHeight(int int_Y) {
        float Total_H = (float) 198;//396.5
        float Final_Y = 0;
        float Gray_KD = (float) TvHeight / BlueHeartRateStart;//4.78
        float Blue_KD = (float) TvHeight / (GreenHeartRateStart - BlueHeartRateStart);//1.20.7
        float Green_KD = (float) TvHeight / (YellowHeartRateStart - GreenHeartRateStart);//1.7432
        float Yellow_KD = (float) TvHeight / (RedHeartRateStart - YellowHeartRateStart);//2.55
        float Red_KD = (float) TvHeight / (bigHeartRate - RedHeartRateStart);//0.93
        if (int_Y <= BlueHeartRateStart) {//灰色区域
            Final_Y = int_Y * Gray_KD;
        }
        //蓝色区域
        if (BlueHeartRateStart < int_Y && int_Y <= GreenHeartRateStart) {
            Final_Y = (BlueHeartRateStart * Gray_KD) + ((int_Y - BlueHeartRateStart) * Blue_KD);
        }
        //绿色区域
        if (GreenHeartRateStart < int_Y && int_Y <= YellowHeartRateStart) {
            Final_Y = (BlueHeartRateStart * Gray_KD) + ((GreenHeartRateStart - BlueHeartRateStart) * Blue_KD) + (int_Y - GreenHeartRateStart) * Green_KD;
        }
        //黄色区域
        if (YellowHeartRateStart < int_Y && int_Y <= RedHeartRateStart) {
            Final_Y = (BlueHeartRateStart * Gray_KD) + ((GreenHeartRateStart - BlueHeartRateStart) * Blue_KD) + (YellowHeartRateStart - GreenHeartRateStart) * Green_KD + (int_Y - YellowHeartRateStart) * Yellow_KD;
        }
        //红色区域
        if (RedHeartRateStart < int_Y && int_Y <= bigHeartRate) {
            Final_Y = (BlueHeartRateStart * Gray_KD) + ((GreenHeartRateStart - BlueHeartRateStart) * Blue_KD) + (YellowHeartRateStart - GreenHeartRateStart) * Green_KD + (RedHeartRateStart - YellowHeartRateStart) * Yellow_KD + (int_Y - RedHeartRateStart) * Red_KD;
        }
//        return ToolUtils.dip2px(getActivity(), Final_Y);
        return ToolUtils.dip2px(getActivity(), Final_Y)-ToolUtils.dp2px(getActivity(),9);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.li_kfzd_bottomstart:

                if (progress != null && progress.isShowing()) {
                } else {
                    if ("开始锻炼".equals(tv_kf_bstart.getText().toString())) {
                        if (progress == null) {
                            progress = new SVProgressHUD(getActivity());
                        }
                        progress.showWithStatus("加载中...");
                        Temp_XL.clear();
                        tv_bottom_max.setText("0次/分");
                        tv_bottom_now.setText("0次/分");
                        tv_bottom_evel.setText("0次/分");
                        tv_endtime.setText("00:00:00");
                        tv_starttime.setText("00:00:00");
                        StartTime = System.currentTimeMillis();
                        getBlueTooth();
                        mX = 0;
                        mHandler.removeMessages(0);
                        mLineView.clear();
                        scrollview.scrollTo(0, 0);
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // TODO Auto-generated method stub
                                // 在此执行耗时工作，执行完毕后调用handler发送消息
                                try {
                                    Thread.sleep(1000);//睡眠6秒 模拟执行耗时任务
                                    mHandler.sendEmptyMessage(0);//在此处设置每页停留时间
                                } catch (Exception e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }
                            }
                        }).start();
                    } else {
                        EndTime = System.currentTimeMillis();
                        if (!TextUtils.isEmpty(tv_bottom_max.getText().toString()) && !TextUtils.isEmpty(tv_bottom_now.getText().toString()) && !TextUtils.isEmpty(tv_bottom_evel.getText().toString())) {
                            getXLData();
                        }
                        tv_kf_bstart.setText("开始锻炼");
                        mHandler.removeMessages(0);
                        Temp_XL.clear();
                    }
                }
                break;


        }
    }

    /**
     * 获取有效时长
     * 有效时长为心率大于40%的时间累计
     */
    public String GetUseableTime() {
        //总时长
        long long_time = System.currentTimeMillis() - StartTime;
        int num = 0;
        for (int i = 0; i < Temp_XL.size(); i++) {
            if (Temp_XL.get(i) > bigHeartRate * 0.64) {
                num++;
            }
        }
        String time = ToolUtils.timeParse((long) ((((double) num / (double) Temp_XL.size())) * long_time));
        return "00:" + time;
    }

    public void setChange() {
        long long_time = System.currentTimeMillis() - StartTime;
        String time = ToolUtils.timeParse(long_time);
        tv_starttime.setText(time);

    }

    /**
     * 关于蓝牙测心率
     */
    private static final int REQUEST_ENABLE_BT = 1;

    public void getBlueTooth() {
        /**
         * 判断当前设备是否支持ble
         */
        if (!getActivity().getPackageManager().hasSystemFeature(
                PackageManager.FEATURE_BLUETOOTH_LE)) {
            System.out.println("不支持BLE设备");
        }
        //得到蓝牙适配器--打开蓝牙
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
            if (progress != null) {
                progress.dismiss();
            }
            //链接蓝牙
            ShowTiShi();
        } else {
            Search();//搜索已经连接的蓝牙
            tv_kf_bstart.setText("结束锻炼");
            Params.IsWakeClock = 1;
            wl.acquire();
        }
    }

    final static private UUID mHeartRateServiceUuid = BleDefinedUUIDs.Service.HEART_RATE;
    final static private UUID mHeartRateCharacteristicUuid = BleDefinedUUIDs.Characteristic.HEART_RATE_MEASUREMENT;

    /**
     * 寻找服务
     */

    private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
        private BluetoothGattCharacteristic mCharacteristic;

        /**
         * 当连接状态发生改变的时候回调的方法
         */
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status,
                                            int newState) {
            //判断蓝牙连接状态
            if (newState == BluetoothProfile.STATE_CONNECTED) {
                System.out.println("设备已连接");
                //寻找设备中的服务
                gatt.discoverServices();
            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                System.out.println("设备已断开连接");
                if (Temp_XL.size() > 0&&"结束锻炼".equals(tv_kf_bstart.getText().toString())) {//断开后就提交
                    if (!TextUtils.isEmpty(tv_bottom_max.getText().toString()) && !TextUtils.isEmpty(tv_bottom_now.getText().toString()) && !TextUtils.isEmpty(tv_bottom_evel.getText().toString())) {
                        getXLData();
                    }
                    tv_kf_bstart.setText("开始锻炼");
                }
            }
        }

        /**
         * 当服务发现后所调用的方法
         */
        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                System.out.println("Services discovered");
                //得到心率信息的service
                BluetoothGattService service = gatt
                        .getService(mHeartRateServiceUuid);
                if (service == null) {
                    Toast.makeText(getActivity(), "没有得到心率服务", Toast.LENGTH_SHORT).show();
//                    CommonUtil.showToask(getActivity(), "没有得到心率服务");
                    System.out.println("没有得到心率服务");
                    if (progress != null) {
                        progress.dismiss();
                    }
                } else {
                    System.out.println("得到心率服务");
//                    if("开始锻炼".equals(tv_kf_bstart.getText().toString())){
//                        tv_kf_bstart.setText("结束锻炼");
//                    }
                    mCharacteristic = service
                            .getCharacteristic(mHeartRateCharacteristicUuid);

                    if (mCharacteristic == null) {
                        System.out.println("不能找到心率");
                        Toast.makeText(getActivity(), "不能找到心率", Toast.LENGTH_SHORT).show();
//                        CommonUtil.showToask(getActivity(), "不能找到心率");
                        if (progress != null) {
                            progress.dismiss();
                        }
                    } else {
                        boolean success = gatt.setCharacteristicNotification(
                                mCharacteristic, true);
                        if (!success) {
                            System.out.println("Enabling notification failed!");
                            return;
                        }

                        BluetoothGattDescriptor descriptor = mCharacteristic
                                .getDescriptor(BleDefinedUUIDs.Descriptor.CHAR_CLIENT_CONFIG);
                        if (descriptor != null) {
                            descriptor
                                    .setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
                            gatt.writeDescriptor(descriptor);
                            System.out.println("Notification enabled");
                        } else {
                            System.out
                                    .println("Could not get descriptor for characteristic! Notification are not enabled.");
                        }
                    }
                }
            } else {
                System.out.println("Unable to discover services");
            }
        }

        /**
         * 当service里边的characteristic发生改变调用
         */
        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt,
                                            BluetoothGattCharacteristic characteristic) {
            //得到心率数据
            if (characteristic.equals(mCharacteristic)) {
                byte[] raw = mCharacteristic.getValue();
//                System.out.println("心率****====" + raw);
                int index = ((raw[0] & 0x01) == 1) ? 2 : 1;
                int format = (index == 1) ? BluetoothGattCharacteristic.FORMAT_UINT8 : BluetoothGattCharacteristic.FORMAT_UINT16;
                int value = mCharacteristic.getIntValue(format, index);
                final int description = value;
//                final String description = value + " bpm";
                Temp_XL.add(description);
//                tv_endtime.setText(GetUseableTime());//有效时长为心率大于40%的时间累计
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
//                        System.out.println("心率：" + description + "Temp_XL" + Temp_XL.size());
                    }
                });

            }
        }

        /* the rest of callbacks are not interested for us */

        @Override
        public void onCharacteristicRead(BluetoothGatt gatt,
                                         BluetoothGattCharacteristic characteristic, int status) {
        }

        @Override
        public void onCharacteristicWrite(BluetoothGatt gatt,
                                          BluetoothGattCharacteristic characteristic, int status) {
        }

        ;

        @Override
        public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
        }

        ;
    };
    private boolean mScanning;

    /**
     * 搜索蓝牙设备
     *
     * @param enable
     */
    private void scanLeDevice(boolean enable) {
        // TODO Auto-generated method stub
        if (enable) {
            mHandler.postDelayed(new Runnable() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    mScanning = false;
                    mBluetoothAdapter.stopLeScan(callback);
                }
            }, 10000);
            mScanning = true;
            mBluetoothAdapter.startLeScan(callback);
        } else {
            mScanning = false;
            mBluetoothAdapter.stopLeScan(callback);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == REQUEST_ENABLE_BT
                && resultCode == Activity.RESULT_CANCELED) {
            getActivity().finish();
            return;
        }
        super.onActivityResult(requestCode, resultCode, data);

    }

    /**
     * 蓝牙搜索的回调方法
     */
    private BluetoothAdapter.LeScanCallback callback = new BluetoothAdapter.LeScanCallback() {

        public void onLeScan(final BluetoothDevice device, int rssi,
                             byte[] scanRecord) {
            System.out.println(device + "****" + device.getName() + "***"
                    + device.getAddress());
            getActivity().runOnUiThread(new Runnable() {
                public void run() {
                    //搜索结果
//                    111
//                    adapter.addDevice(device);
//                    adapter.notifyDataSetChanged();
                }
            });
        }
    };

    /**
     * 关于弹窗提示
     */
    public void ShowTiShi() {
        // 加载布局
        LayoutInflater inflater = LayoutInflater
                .from(getActivity());
        View view = inflater.inflate(R.layout.open_bluetooth_dialog, null);
        TextView op_cancle = (TextView) view.findViewById(R.id.op_cancle);
        TextView op_sure = (TextView) view.findViewById(R.id.op_sure);
        // 创建popupwindow对话框
        final PopupWindow pop = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT);
        pop.setFocusable(true);// 必须有，因为要获得焦点进行输入
        // 设置此参数，点击外边可消失
        pop.setBackgroundDrawable(new BitmapDrawable());
        // 点击其他除了popupwindow对话框的地方就可使popupwindow对话框消失
        pop.setOutsideTouchable(true);
//        pop.showAtLocation(liFr, Gravity.CENTER, 0, 0);// 显示位置以某控件为中心
        if (Build.VERSION.SDK_INT >= 24) {
            int[] a = new int[2];
            pcTitle.getLocationInWindow(a);
            pop.showAtLocation((getActivity()).getWindow().getDecorView(), Gravity.NO_GRAVITY, 0, a[1] + pcTitle.getHeight());
        } else {
            pop.showAsDropDown(pcTitle);
        }
        op_cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pop.dismiss();
            }
        });
        op_sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pop.dismiss();
                openSettingaa();
            }
        });
    }

    /**
     * 打开蓝牙设置
     */
    private void openSettingaa() {
        Intent intent = new Intent();
        intent.setAction(Settings.ACTION_BLUETOOTH_SETTINGS);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        try {
            startActivity(intent);
        } catch (ActivityNotFoundException ex) {
            ex.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 搜索蓝牙 获取已连接的
     */
    public void Search() {
        HaveClectNum = false;
        BltManager.getInstance().initBltManager(getActivity());
        //注册蓝牙扫描广播
        blueToothRegister();
        new Thread(new Runnable() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                // 在此执行耗时工作，执行完毕后调用handler发送消息
                try {
                    Thread.sleep(60000);//睡眠一分钟 模拟执行耗时任务
                    mHandler_m.sendEmptyMessage(0);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }).start();
//        if (blueToothRegister()== false) {
//            CommonUtil.showToask(getActivity(), "未检测到已配对的心率设备！");
//            if(progress!=null){
//                progress.dismiss();
//            }
//        }
        BltManager.getInstance().clickBlt(getActivity(), BltContant.BLUE_TOOTH_SEARTH);
    }

    /**
     * 注册蓝牙回调广播
     */
    private boolean blueToothRegister() {
        BltManager.getInstance().registerBltReceiver(getActivity(), new BltManager.OnRegisterBltReceiver() {
            /**
             * 搜索到新设备
             *
             * @param device
             */
            @Override
            public void onBluetoothDevice(BluetoothDevice device) {
                //获得已连接的设备
                if ("连接完成".equals(BltManager.getInstance().bltStatus(device.getBondState()))) {
                    HaveClectNum = true;
                    System.out.println("连接完成" + device.getName());
                    //根据UUid过滤一下
//                    if (device.getUuids().equals(HEART_RATE_SERVICE)) {
                    device.connectGatt(getActivity().getApplicationContext(), false,
                            mGattCallback);
//                    }
//                    CommonUtil.showToask(getActivity(), "开始锻炼");
                }
                System.out.println("搜索到新设备" + device.getName());
            }


            /**
             * 连接中
             *
             * @param device
             */
            @Override
            public void onBltIng(BluetoothDevice device) {

            }


            /**
             * 连接完成
             *
             * @param device
             */
            @Override
            public void onBltEnd(BluetoothDevice device) {
                HaveClectNum = true;
                System.out.println("已经和" + device.getName() + "完成连接");
                device.connectGatt(getActivity().getApplicationContext(), false,
                        mGattCallback);
            }

            /**
             * 取消连接
             *
             * @param device
             */
            @Override
            public void onBltNone(BluetoothDevice device) {


            }
        });
        return HaveClectNum;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
//页面关闭的时候 要断开蓝牙
// 反注册
        try {
            BltManager.getInstance().unregisterReceiver(getActivity());
        } catch (Exception o) {
        }
    }

}